package com.houdoudou.customer.buy;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Branch;
import com.houdoudou.bean.Car;
import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.OrderProduct;
import com.houdoudou.bean.Product;
import com.houdoudou.bean.Supplier;
import com.houdoudou.customer.FrgBuyOfActMain;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.AsynImageLoader;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.ListViewUtil;
import com.houdoudou.customer.me.LoginAct;
import com.houdoudou.customer.sqlite.CarDao;
import com.houdoudou.customer.sqlite.CarManagement;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Instrumentation;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BuyCarAct extends Activity{
    

	ListView listView;
	JSONArray ja_BuyCar=new JSONArray();
	ParentListAdapter parentAdapter;
	AsynImageLoader imageLoader;
	TextView total;
	Button settle;
	ImageButton back;
	int onlyParentCarNo=-1;
    Handler buycarHandler;
    JSONObject carJO=new JSONObject();
 
    private static String IS_SELECTED="Is_Selected";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_buycar);
		total= (TextView) findViewById(R.id.tv_selectedtotal_act_buycar);
		settle= (Button) findViewById(R.id.btn_settle_act_buycar);
		back= (ImageButton) findViewById(R.id.back_act_buycar);
		settle=(Button) findViewById(R.id.btn_settle_act_buycar);
		parentAdapter=new ParentListAdapter(this);
		listView=(ListView) findViewById(R.id.listview_parent_act_buycar);
		listView.setAdapter(parentAdapter);
		imageLoader= new AsynImageLoader(this);
	    carJO.put(Car.MACHINE, Constant.machineJO.getInt(Machine.ID));
	    
			
	    back.setOnClickListener(
	    		new View.OnClickListener() {			
					@Override
					public void onClick(View v) {				
							new Thread () { 
								public void run () { 
								try { 									
								Instrumentation inst= new Instrumentation(); 
								inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
								} catch(Exception e) { 
								e.printStackTrace(); 
								         } 
								  } 
								}.start();
	                      }});
		
		settle.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stu
				if(Constant.customerJO==null){
					Intent intent= new Intent(BuyCarAct.this, LoginAct.class);
					startActivity(intent);
					return;
				}
				if(onlyParentCarNo==-1){
					CommonFunction.alert(BuyCarAct.this, "无法提交", "请先选择产品"); return;
				}
				//构造订单数据。
				JSONObject orderJO= Order.createBasicOrderJO(ja_BuyCar.getJSONObject(onlyParentCarNo));
				
			   // 构造订单产品表需要的数据。并统计订单价格等值。
					JSONArray orderProducts= new JSONArray();
					int productNum=0; //产品数量
					int volume=0; //总体积
					int boxNum=0; //箱格数量		
					double moneyProduct=0; //商品金额
					double moneyFreight=0; //运费。
				
					for(int i=0;i<ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").size();i++){
						System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^i="+i+"^^^^^^^^^^^^^^^^");
						JSONObject currentCarJO=ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").getJSONObject(i);
						if(currentCarJO.getBoolean(IS_SELECTED)){
							JSONObject orderProductJO= new JSONObject();
							orderProductJO.put(OrderProduct.PRODUCTID, currentCarJO.getInt(Car.PRODUCT));
							orderProductJO.put(OrderProduct.PRODUCTNAME, currentCarJO.getString(OrderProduct.PRODUCTNAME));
							orderProductJO.put(OrderProduct.PRODUCTTYPE,currentCarJO.getInt(OrderProduct.PRODUCTTYPE));
							orderProductJO.put(OrderProduct.BRANCHID, currentCarJO.getInt(Car.BRANCH));
							orderProductJO.put(OrderProduct.BRANCHNAME, currentCarJO.getString(OrderProduct.BRANCHNAME));
							orderProductJO.put(OrderProduct.BRANCHVOLUME, currentCarJO.getInt(OrderProduct.BRANCHVOLUME));
							orderProductJO.put(OrderProduct.BRANCHPRICE,currentCarJO.getDouble(OrderProduct.BRANCHPRICE));
							orderProductJO.put(OrderProduct.BRANCHNUM,currentCarJO.getInt(Car.NUMBER));
							orderProductJO.put(OrderProduct.BRANCHNUM,currentCarJO.getString(Car.NUMBER));
						
							orderProductJO.put(OrderProduct.DIR,currentCarJO.getString(OrderProduct.DIR));
							volume+=currentCarJO.getInt(OrderProduct.BRANCHVOLUME)*currentCarJO.getInt(Car.NUMBER);
							productNum+=currentCarJO.getInt(Car.NUMBER);
							moneyProduct+=currentCarJO.getDouble(OrderProduct.BRANCHPRICE)*currentCarJO.getInt(Car.NUMBER);
						 orderProducts.add(orderProductJO);
						}
					}
					if(orderProducts.size()<=0){
						CommonFunction.alert(BuyCarAct.this, "无法提交", "请先选择产品"); return;
					}
					//
					orderJO.put("products", orderProducts);
					//产品汇总字段
					orderJO.put(Order.MONEYPRODUCT, moneyProduct);
					orderJO.put(Order.PRODUCTNUM, productNum);
					orderJO.put(Order.VOLUME, volume);
					boxNum= volume/orderJO.getInt(Order.BOXVOLUME)+1; 
					orderJO.put(Order.BOXNUM, boxNum);
					moneyFreight=boxNum*orderJO.getDouble(Order.BOXFEECU);
					orderJO.put(Order.MONEYFREIGHT, moneyFreight);
					orderJO.put(Order.MONEYCU, moneyFreight+moneyProduct);			
					Intent intent= new Intent(BuyCarAct.this, PlaceOrderAct.class);
					intent.putExtra("orderJO", orderJO.toString());				
					startActivity(intent);		
			}
		});
		 
		
	    
	}
	 
		@Override
		protected void onResume() {
			// TODO Auto-generated method stub
			super.onResume();

			if(FrgBuyOfActMain.PullSuccess) {
				onlyParentCarNo=-1; refresh_data_fromsqlite();caculate_total();
				}else{
				 	CommonFunction.alert(BuyCarAct.this, "无法使用购物车", "未连接服务器，更新数据");
				}
			
		}
	 private void caculate_total(){
		 int num=0;
		 double money=0;
		 if(onlyParentCarNo!=-1){
			 for(int j=0;j<ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").size();j++){
					JSONObject record=ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").getJSONObject(j);
					if(record.getBoolean(IS_SELECTED)){
						num+=record.getInt(Car.NUMBER);
						money+=record.getInt(Car.NUMBER)*record.getDouble(OrderProduct.BRANCHPRICE);
						//System.out.println("---------------"+i+"---"+j+"-Slected---------------");
					}
				 }
		 }
		
		String words="("+num+"份"+money+"元)";	 
		total.setText(words); 
	 }
	private void refresh_data_fromsqlite(){
		
		ja_BuyCar.clear();
		
		for(int x=0;x<FrgBuyOfActMain.suppliersJA.size();x++){	
			JSONObject carParentJO=JSONObject.fromObject( FrgBuyOfActMain.suppliersJA.getJSONObject(x)); //如果直接引用，remove会改变原值，这里相当于复制了原值
			JSONArray ja_index_product=carParentJO.getJSONArray("sorts");
			carParentJO.remove("sorts");
			carJO.put(Car.SUPPLIER, carParentJO.getString(Supplier.TELNUM));
			carJO.put(Car.TIMEFLAG, carParentJO.getInt(Car.TIMEFLAG));
			
			JSONArray Saved_Branch_JA=new CarDao(BuyCarAct.this).queryBySupplier(carJO);
			
			 for(int i=Saved_Branch_JA.size()-1;i>=0;i--){
	  			 int Product_ID=Saved_Branch_JA.getJSONObject(i).getInt(Car.PRODUCT);
	  			 int Branch_Num=Saved_Branch_JA.getJSONObject(i).getInt(Car.NUMBER);
	  			 int Branch_ID=Saved_Branch_JA.getJSONObject(i).getInt(Car.BRANCH);
	  			 int J = 0,K=0;
	  			 double branchPrice=-1;  String branchName=""; int branchVolume=-1;
	  			 String productName=""; String productDir=""; int productType=-1;
	  			    for(int j=0;j<ja_index_product.size();j++){
	  			    	for(int k=0;k<ja_index_product.getJSONObject(j).getJSONArray("products").size();k++){
	  			    		if(Product_ID==ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getInt(Product.ID)){
	  			    		 J=j; K=k;
	  			    	     productName=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getString(Product.NAME);
	  			    	     productDir=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getString(Product.DIR);
	  			    	     productDir+="0.jpg";
	  			    	     productType=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getInt(Product.TYPE);
	  			    	   for(int q=0;q<ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").size();q++){
				    			   if(Branch_ID==ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getInt(Branch.ID)){
				    				   branchName=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getString(Branch.NAME);
				    			       branchPrice=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getDouble(Branch.PRICE);
				    			       branchVolume=ja_index_product.getJSONObject(j).getJSONArray("products").getJSONObject(k).getJSONArray("branches").getJSONObject(q).getInt(Branch.VOLUME);
				    			       break;}
				    		   }		
	  			    		}
	  			    	}
	  			    }
	  			if(branchPrice==-1){
	  				 new CarDao(BuyCarAct.this).deleteOneRecord(Saved_Branch_JA.getJSONObject(i));
	  				 Saved_Branch_JA.remove(i);
	  			}else{
	  				Saved_Branch_JA.getJSONObject(i).put( OrderProduct.PRODUCTNAME,productName);
	  				Saved_Branch_JA.getJSONObject(i).put( OrderProduct.DIR, productDir);
	  				Saved_Branch_JA.getJSONObject(i).put( OrderProduct.PRODUCTTYPE,productType);
	  				Saved_Branch_JA.getJSONObject(i).put( OrderProduct.BRANCHPRICE,branchPrice);	
	  				Saved_Branch_JA.getJSONObject(i).put( OrderProduct.BRANCHNAME,branchName);	 
	  				Saved_Branch_JA.getJSONObject(i).put( OrderProduct.BRANCHVOLUME,branchVolume);
	  				
	  				Saved_Branch_JA.getJSONObject(i).put( IS_SELECTED,false);
	  			}    
	  			    
	  		 }
			
			if(Saved_Branch_JA.size()>0){	
				carParentJO.put("cars", Saved_Branch_JA);
				carParentJO.put( IS_SELECTED,false);
			   ja_BuyCar.add(carParentJO);
			}
		}
		
		/*// 1查询所有的内容，根据 供应商和供应时间，分类。
		CarManagement carmanagement= new CarManagement(this);
		List<String>  tel_list= new ArrayList<String>();
		List<String>  time_list= new ArrayList<String>();		
		
		JSONArray all= carmanagement.queryAll();
		for(int i=0;i<all.size();i++){
			String tel=all.getJSONObject(i).getString("Supplier_Telnum");
			String time=all.getJSONObject(i).getString("Arrive_Time");
			if(!(tel_list.contains(tel)&&time_list.contains(time))){
				tel_list.add(tel);
				time_list.add(time);
				
			}			
		}
		
	   /2 根据分类，查询数据库，生成所需数据。删除不存在的供应商和商品，
		for(int i=0;i<tel_list.size();i++){
			//a 从主函数中的 Frg中 获取供应商名字
			String Supplier_Name = "";
			String Service_Telnum="";
			for(int j=0;j<FrgBuyOfActMain.list_data_suppliers.size();j++){
				String temptel= (String) FrgBuyOfActMain.list_data_suppliers.get(j).get("Supplier_Telnum");
				String temptime= (String) FrgBuyOfActMain.list_data_suppliers.get(j).get("Arrive_Time");
				if(temptel.equals(tel_list.get(i))&&temptime.equals(time_list.get(i))){
					Supplier_Name=(String) FrgBuyOfActMain.list_data_suppliers.get(j).get("Supplier_Name");
					Service_Telnum=(String) FrgBuyOfActMain.list_data_suppliers.get(j).get("Service_Telnum");
				
			  }
			}   
			
			//这里共用 buy frg里面的验证，如果某时间段内的供应商不存在，则删除本地数据库。
			if(Supplier_Name.isEmpty()||Service_Telnum.isEmpty()){
				JSONObject branch= new JSONObject();
				branch.put("Supplier_Telnum", tel_list.get(i));
				branch.put("Arrive_Time",time_list.get(i) );
				carmanagement.deleteOneSupplier(branch);
		    // 存在则加入。
			}else{
			JSONObject shop= new JSONObject();
			shop.put("Supplier_Name",Supplier_Name);
			shop.put("Arrive_Time",time_list.get(i));
			shop.put("Service_Telnum",Service_Telnum);
			shop.put("Is_Selected",false);
			shop.put("cars", carmanagement.queryBySupplier(tel_list.get(i), time_list.get(i)));		
			ja_BuyCar.add(shop);
			}
		// 联网检测数据库内产品。更新价格等参数。如果产品，或者子配不存在则删除。
			
				
		} */
	   	
	   parentAdapter.notifyDataSetChanged();
	}
	

	
	
class ParentListAdapter extends BaseAdapter {
		   
		
	    private LayoutInflater layoutInflater;  
	    private Context context;  
	    
	public ParentListAdapter(Context context) {
		
					
			this.context = context;
		    this.layoutInflater=LayoutInflater.from(context); 
		}
	
	
	final class Zujian{  
	 
        public ListView listviewchild;
        public TextView shopname, arrivetime;   
        public CheckBox select;
   }   //end of Zujian

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		 return ja_BuyCar.size();  
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		 return ja_BuyCar.getJSONObject(position);  
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position; 
	}
 
	@Override
	public View getView(int position, View  convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int parentID = position;   
		 Zujian zj=null;  
	        if(convertView==null){  
	            zj=new Zujian();  
	            //获得组件，实例化组件  
	            convertView=layoutInflater.inflate(R.layout.list_parent_act_buycar, null);  
	            zj.listviewchild= (ListView) convertView.findViewById(R.id.listviewchild_listparent_actbuycar);
	            zj.shopname=(TextView) convertView.findViewById(R.id.tv_shopnme_listparent_actbuycar);
	            zj.arrivetime=(TextView) convertView.findViewById(R.id.tv_arrivetime_listparent_actbuycar);
	            zj.select= (CheckBox) convertView.findViewById(R.id.ck_choose_listparent_actbuycar);
	            convertView.setTag(zj);  
	            System.out.println("position----"+position+"------inflated");
	        }else{   System.out.println("position----"+position+"-------not inflated");
	            zj=(Zujian)convertView.getTag();  
	        }  		        						  
	        //绑定数据     
	                 zj.listviewchild.setAdapter(new ChildListAdapter(context,position));
	                ListViewUtil.setListViewHeightBasedOnChildren(zj.listviewchild);
	                
	                 zj.shopname.setText( ja_BuyCar.getJSONObject(position).getString(Supplier.NAME));
	                 String temp="("+ja_BuyCar.getJSONObject(position).getString("timeAA")+")";
	                 zj.arrivetime.setText(temp);
	                 
	                 if(ja_BuyCar.getJSONObject(position).getBoolean(IS_SELECTED)){
	                	 zj.select.setChecked(true);
	                 }else{
	                	 zj.select.setChecked(false);
	                 }
	                 
	                 zj.select.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							// TODO Auto-generated method stub
							boolean isSelectValid=false;
							if(isChecked){
								if(onlyParentCarNo!=-1&&onlyParentCarNo!=parentID){
								Toast.makeText(BuyCarAct.this, "一次只能提交一家店铺，已选其他商品已被取消选择", Toast.LENGTH_SHORT).show();
								ja_BuyCar.getJSONObject(onlyParentCarNo).put(IS_SELECTED, false);	
								for(int i=0;i<ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").size();i++){
									ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").getJSONObject(i).put(IS_SELECTED, false);
								}  }
								
						   ja_BuyCar.getJSONObject(parentID).put(IS_SELECTED, true);								
							for(int i=0;i<ja_BuyCar.getJSONObject(parentID).getJSONArray("cars").size();i++){
								ja_BuyCar.getJSONObject(parentID).getJSONArray("cars").getJSONObject(i).put(IS_SELECTED, true);
							}	
							onlyParentCarNo=parentID;
							parentAdapter.notifyDataSetChanged();
						    caculate_total();	
					      }else{
						      ja_BuyCar.getJSONObject(parentID).put(IS_SELECTED, false); 
					            }	
							
						}
					});
	                 
	        return convertView;
           } 
      }// end Adapter
	

class ChildListAdapter extends BaseAdapter {
	   
	
    private LayoutInflater layoutInflater;  
    private Context context;  
    private int parentPosition;
        public ChildListAdapter(Context context , int parentPosition) {
			
		this.context = context;
	    this.layoutInflater=LayoutInflater.from(context); 
	    this.parentPosition=parentPosition;
	}


    final class Zujian{  
         public TextView product,branch,price,num; 
         public CheckBox select;
         public  ImageView img;
         public Button increase,decrease;
        }   //end of Zujian

          @Override
       public int getCount() {
	// TODO Auto-generated method stub
        	  if(ja_BuyCar.size()==0){ return 0;
        	  }else{
	      return ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").size(); }
       }

      @Override
       public Object getItem(int position) {
	// TODO Auto-generated method stub
	          return ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(position);  
          }

    @Override
     public long getItemId(int position) {
	// TODO Auto-generated method stub
	       return position; 
       }

               @Override
    public View getView(int position, View  convertView, ViewGroup parent) {
	// TODO Auto-generated method stub
	final int childID = position;   
	 Zujian zj=null;  
        if(convertView==null){  
            zj=new Zujian();  
            //获得组件，实例化组件  
            convertView=layoutInflater.inflate(R.layout.list_child_act_buycar, null);  
            zj.img=(ImageView) convertView.findViewById(R.id.img_product_listchild_actbuycar);
            zj.select= (CheckBox) convertView.findViewById(R.id.ck_choose_listchild_buycaract);
            zj.num=(TextView) convertView.findViewById(R.id.tv_branchnum_listchild_buycaract);
            zj.branch=(TextView) convertView.findViewById(R.id.tv_branchname_listchild_buycaract);
            zj.product=(TextView) convertView.findViewById(R.id.tv_productname_listchild_buycaract);
            zj.price=(TextView) convertView.findViewById(R.id.tv_branchprice_listchild_buycaract);
            zj.increase=(Button) convertView.findViewById(R.id.btn_increase_listchild_actbuycar);
            zj.decrease=(Button) convertView.findViewById(R.id.btn_decrease_listchild_actbuycar);
            convertView.setTag(zj);  
            System.out.println("position----"+position+"------inflated");
        }else{   System.out.println("position----"+position+"-------not inflated");
            zj=(Zujian)convertView.getTag();  
        }  		        						  
        //绑定数据  
        JSONObject record=ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID);
        zj.num.setText(String.valueOf(record.getInt(Car.NUMBER)));
        zj.price.setText(String.valueOf(record.getDouble(OrderProduct.BRANCHPRICE)));
        zj.branch.setText(record.getString(OrderProduct.BRANCHNAME));
        zj.product.setText(record.getString(OrderProduct.PRODUCTNAME));
        imageLoader.showImageAsyn(zj.img, record.getString(OrderProduct.DIR), R.drawable.p3);
        
        if(ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID).getBoolean("Is_Selected")){
       	 zj.select.setChecked(true);
        }else{
       	 zj.select.setChecked(false);
        }
        
        zj.select.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
        	
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub	
				
				
				if(isChecked){
					if(onlyParentCarNo!=-1&&onlyParentCarNo!=parentPosition){
					Toast.makeText(BuyCarAct.this, "一次只能提交一家店铺，已选其他商品已被取消选择", Toast.LENGTH_SHORT).show();
					ja_BuyCar.getJSONObject(onlyParentCarNo).put(IS_SELECTED, false);	
					for(int i=0;i<ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").size();i++){
						ja_BuyCar.getJSONObject(onlyParentCarNo).getJSONArray("cars").getJSONObject(i).put(IS_SELECTED, false);
					}  }
					
			   
					ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID).put(IS_SELECTED, true);
				
				onlyParentCarNo=parentPosition;
				parentAdapter.notifyDataSetChanged();
			    caculate_total();	
		      }else{
		    	  ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID).put(IS_SELECTED, false);
		    	  ja_BuyCar.getJSONObject(parentPosition).put("Is_Selected", false);
		    	  boolean isNoChoose=true;	
						   
							for(int j=0;j<ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").size();j++){
								if(ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(j).getBoolean(IS_SELECTED)){
									isNoChoose=false;  break;}	
							}
				if(isNoChoose){
					onlyParentCarNo=-1;
				}	 
		            }		
			   	parentAdapter.notifyDataSetChanged();		 				 
				caculate_total();
			    System.out.println("----CHILD CHECK-----");
			}
			}
		);
        
        zj.increase.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int numOld=ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID).getInt(Car.NUMBER);
				ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID).put(Car.NUMBER, numOld+1);			
				new CarDao(context).updateOneRecord(ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID));
				parentAdapter.notifyDataSetChanged();
				caculate_total();
			}
		});
        
        zj.decrease.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int numOld=ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID).getInt(Car.NUMBER);
				if(numOld>1){
					ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID).put(Car.NUMBER, numOld-1);			
					new CarDao(context).updateOneRecord(ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID));
					
				}else{
		             new CarDao(context).deleteOneRecord(ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").getJSONObject(childID));
		             ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").remove(childID);
		             if(ja_BuyCar.getJSONObject(parentPosition).getJSONArray("cars").size()==0){
		            	 ja_BuyCar.remove(parentPosition); 
		            	 if(onlyParentCarNo==parentPosition) onlyParentCarNo=-1;
		             }
				}
				
				parentAdapter.notifyDataSetChanged();
				caculate_total();
				
			}
		});
        
        return convertView;
       } 
         }// end Adapter

   

  }
